home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 1440 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.4 KB  |  60 lines

  1. Path: ix.netcom.com!netnews
  2. From: miker3@ix.netcom.com (Mike Rubenstein)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Quick, easy question on externs...
  5. Date: Thu, 11 Jan 1996 02:19:23 GMT
  6. Organization: Netcom
  7. Message-ID: <30f46f5b.430017088@nntp.ix.netcom.com>
  8. References: <30F4333C.41A9@omni.voicenet.com>
  9. NNTP-Posting-Host: ix-dc9-08.ix.netcom.com
  10. X-NETCOM-Date: Wed Jan 10  6:18:00 PM PST 1996
  11. X-Newsreader: Forte Agent .99c/16.141
  12.  
  13. David Zuckman <dzuckman@omni.voicenet.com> wrote:
  14.  
  15. |>I got two source files:
  16. |>
  17. |>z1.cpp
  18. |>======
  19. |>    #include <iostream.h>
  20. |>
  21. |>    extern int const x;
  22. |>
  23. |>    void main( void ) {
  24. |>        x;
  25. |>    }
  26. |>
  27. |>z2.cpp
  28. |>======
  29. |>    int const x = 5;
  30. |>
  31. |>They compile and link fine (I'm using MS Visual C++ 2.1).
  32. |>
  33. |>I change the line in z1.cpp that reads
  34. |>        x;
  35. |>to
  36. |>        cout << x;
  37. |>and I get
  38. |>
  39. |>    Incrementally linking...
  40. |>    LINK : performing full link
  41. |>    z1.obj : error LNK2001: unresolved external symbol "?x@@3HB
  42. (int const  x)"
  43. |>    WinDebug/dbx.exe : error LNK1120: 1 unresolved externals
  44. |>
  45. |>What gives?
  46.  
  47. Looks like the optimizer allowed you to get away with incorrect code
  48. initially.  What probably happend is that the compiler realized that
  49. x; doesn't do anything useful and eliminated the statement so there
  50. was no reference to x in the object module for z1.cpp.
  51.  
  52. In C++, const implies static linkage so the x defined in z2.cpp is not
  53. available outside that file.  To fix this, change the definition in
  54. z2.cpp to
  55.  
  56.     extern int const x = 5;
  57.  
  58.  
  59. Michael M Rubenstein
  60.